<script setup>
import {ref,reactive} from "vue";
import http from "@/utils/http";

import TopHead from "@/components/TopHead.vue";
import Banners from "@/components/Banners.vue"
import StoryList from "@/components/StoryList.vue"
import Loading from "@/components/Loading.vue"


let stories=reactive({topStories:[],StoryList:[]});
http.get("/stories/latest").then(result=>{
  stories.topStories=result.data.top_stories;//轮播图
  stories.storyList=result.data.stories;//列表

  console.log("首页得到服务器的结果==>",result);
  //console.log("首页得到topstories==>",stories.topStories)
});
 let isShowLoading=ref(false);//定义响应数据是否滚到了底部

 //格式为 20230101 
 let date=new Date();//获取日期
 let year=date.getFullYear();
 let month=date.getMonth()+1; //0-11
 month=month<10 ? "0"+month:month; //补零 (三目运算 三元运算)
 let day=date.getDate(); //当前日期日 
 day=day>9?day:"0"+day;
 let isStop=false;//是否加载更多
 


 window.onscroll=()=>{  //窗口滚动
  let scrollHeight=document.documentElement.scrollHeight;//滚动高度,非固定整个页面
  let clientHeight=document.documentElement.clientHeight;//可视高度,固定
  let scrollTop=document.documentElement.scrollTop;//滚动距离,滚动条

  if(scrollHeight==clientHeight+scrollTop && !isShowLoading.value &&!isStop){
    console.log("到底了")
    isShowLoading.value=true;
    http.get(`stories/before/${year}${month}${day}`).then((result)=>{
      console.log("获取的结果",result.data.stories);
      //加载日期分割线
      stories.storyList.push({
        id:Date.now(),
        timeline:`${year}年${month}月${day}日`,
        showtime:true
      });
      stories.storyList=stories.storyList.concat(result.data.stories);//合并原来和新的数据
      isShowLoading.value=false;

      day=parseInt(day)-1;//如果当前获取数据成功 把日期-1改为前一天的日期
      if(day<1) isStop=true;//如果下一次加载日期小于1则停止加载
      day=day>9?day:"0"+day;
    });

  }
  //console.log("可滚动高度=>",scrollHeight,"可视高度=>",clientHeight,"滚动距离=>",scrollTop)
 }

</script>

<template>
  <main>
    <!-- 头 -->
     <TopHead></TopHead>
     
     <Banners :top-stories="stories.topStories"></Banners>

     <StoryList :story-list="stories.storyList"></StoryList>

    <Loading v-show="isShowLoading"></Loading>
     
  </main>
</template>
